package com.foreknow.servlet;

import com.foreknow.entity.User;
import com.foreknow.service.UserService;
import com.google.gson.Gson;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

@WebServlet({"/api/sign-in","/api/sign-up"})
public class UserServlet extends HttpServlet {
    private UserService userService;
    public UserServlet() {
        super();
        userService = new UserService();
    }

    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String uri = request.getRequestURI();
        //要将登录成功或失败的一些提示信息保存到一个Map集合
        Map<String,Object> data = new HashMap<>();
        Gson gson = new Gson();
        if(uri.endsWith("/api/sign-in")){
            //获取请求参数
            String username = request.getParameter("username");
            String password = request.getParameter("password");

            if(userService.signIn(username,password)){
                data.put("errorCode",0);
                data.put("message","登录成功!");
                //根据姓名查询到当前的用户信息并保存到map中
                User user =  userService.getUserByName(username);
                //将密码设置为空(为了安全)
                user.setPassword("");
                data.put("user",user);

            }else {
                data.put("errorCode",-1);
                data.put("message","登录失败!");
                data.put("user",null);
            }
        }else if(uri.endsWith("/api/sign-up")) {
            String username = request.getParameter("username");
            String password = request.getParameter("password");
            String account = request.getParameter("account");
            String phone = request.getParameter("phone");
            String email = request.getParameter("email");

            User user = new User(null,username,account,password,phone,email,null);

            if(userService.signUp(user)){
                user = userService.getUserByName(username);
                data.put("errorCode",0);
                data.put("message","注册成功，正在登录!");
                user.setPassword("");
                data.put("user",user);
            }else {
                data.put("errorCode",-1);
                data.put("message","注册失败!");
            }
        }
        //将map对象转成json字符串
        String json = gson.toJson(data);
        response.getWriter().write(json);
        data.clear();
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doPost(request,response);
    }
}